#include <iostream>
#include <sstream>
#include <memory>
#include <string>
#include <jsoncpp/json/json.h>

// 序列化代码测试
// 将这多种数据对象组织成为⼀个字符串
void serialize()
{
    const char *name = "小明";
    int age = 20;
    float score[] = {77, 55.5, 99};

    Json::Value val;
    val["姓名"] = name;
    val["年龄"] = 20;
    val["成绩"].append(score[0]);
    val["成绩"].append(score[1]);
    val["成绩"].append(score[2]);

    Json::StreamWriterBuilder swb;
    swb["emitUTF8"] = true;
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());

    std::stringstream ss;
    int ret = sw->write(val, &ss); // 把val序列化的结果放进ss里
    if (ret != 0)
    {
        std::cout << "write fail!\n";
        return ;
    }
    std::cout << ss.str() << std::endl;

}

// 反序列化测试代码
void unserialize(std::string& str)
{
    Json::Value val;
    Json::CharReaderBuilder crb;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());

    std::string err;
    bool ret = cr->parse(str.c_str(), str.c_str()+str.size(), &val, &err);
    if(ret == false)
    {
        std::cout <<"parse fail!\n";
        return;
    }
    std::cout << val["姓名"].asString() << std::endl;
    std::cout << val["年龄"].asInt() << std::endl;
    int sz = val["成绩"].size();
    for(int i = 0; i < sz; i++)
        std::cout << val["成绩"][i] << std::endl;
}

int main()
{
    std::string str = R"({"姓名":"⼩明", "年龄":18, "成绩":[76.5, 55, 88]})";
    unserialize(str);

    return 0;
}